package com.hsgene.medicine.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.medicine.condition.GeneticMedicineCondition;
import com.hsgene.medicine.domain.GeneticCancerMedicine;
import com.hsgene.medicine.domain.GeneticMedicine;
import com.hsgene.medicine.dto.DaCancerDto;
import com.hsgene.medicine.dto.GeneticCancerMedicineDto;
import com.hsgene.medicine.dto.GeneticMedicineDto;
import com.hsgene.medicine.persistence.MedicineRepository;
import com.hsgene.medicine.service.MedicineService;
import com.hsgene.medicine.service.api.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @desc: 药物管理service
 * @author: 江承良
 * @date: 2018/8/15 10:04
 */
@Service
public class MedicineServiceImpl implements MedicineService {
    @Value("${kt.drug.page.url}")
    private String drugPageUrl;

    @Value("${kt.drug.page.apiKey}")
    private String apiKey;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private GeneratorService generatorService;

    @Autowired
    private MedicineRepository medicineRepository;

    /**
     * 获取知识库药物列表
     *
     * @param query  搜索条件
     * @param page   页码
     * @param offset 每页显示数量
     * @return 列表数据信息
     */
    @Override
    public ApiResult drugPage(String query, Integer page, Integer offset) {
        //参数设置
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("keyword", query);
        map.add("page", page);
        map.add("offset", offset);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("apiKey", apiKey);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(drugPageUrl, httpEntity, String.class);
        String s = responseEntity.getBody();
        Object parse = JSONUtils.parse(s);
        return new ApiResult(200, "success", "获取列表成功", parse);
    }

    /**
     * 添加基因检测药物
     *
     * @param medicineDto 药物信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult insertGeneticMedicine(GeneticMedicineDto medicineDto) {
        int drugNameCount = medicineRepository.geneticMedicineRepeat(medicineDto.getDrugName());
        if(drugNameCount>0){
            return new ApiResult(5001, "failed", "药物已存在，请勿重复添加", null);
        }
        GeneticMedicine geneticMedicine = new GeneticMedicine();
        ApiResult<GeneratorDto> generator = generatorService.getGenerator("genetic_testing_drug", null);
        geneticMedicine.setId(generator.getData().getSerialNumber());
        geneticMedicine.setDrugName(medicineDto.getDrugName());
        geneticMedicine.setDrugAlias(medicineDto.getDrugAlias());
        geneticMedicine.setCreateDateTime(new Date());
        geneticMedicine.setDelFlag(false);
        int i = medicineRepository.insertGeneticMedicine(geneticMedicine);
        if (i > 0) {
            return new ApiResult(200, "success", "添加成功", null);
        } else {
            return new ApiResult(500, "failed", "添加失败", null);
        }
    }

    /**
     * 基因检测药物列表
     *
     * @param geneticMedicineCondition 查询条件
     * @return 列表信息
     */
    @Override
    public ApiResult<Pagination<GeneticMedicineDto>> geneticMedicinePage(GeneticMedicineCondition geneticMedicineCondition) {
        FieldChecker.checkEmpty(geneticMedicineCondition.getLimitHelper(), "limitHelper");
        int count = medicineRepository.geneticMedicineCount(geneticMedicineCondition);
        Pagination<GeneticMedicineDto> pagination = Pagination.newInstance(geneticMedicineCondition.getLimitHelper(), count);
        List<GeneticMedicineDto> geneticMedicineDtos = new ArrayList<>();
        if (count > 0) {
            geneticMedicineDtos = medicineRepository.geneticMedicineDtos(geneticMedicineCondition);
        }
        pagination.setResult(geneticMedicineDtos);
        return new ApiResult<>(200, "success", "查询列表成功", pagination);
    }

    /**
     * 根据id获取基因检测药物信息
     *
     * @param id 基因检测药物id
     * @return 基因检测药物信息
     */
    @Override
    public ApiResult<GeneticMedicineDto> geneticMedicineById(String id) {
        GeneticMedicineDto geneticMedicineDto = medicineRepository.geneticMedicineById(id);
        return new ApiResult<>(200, "success", "查询基因检测药物成功", geneticMedicineDto);
    }

    /**
     * 修改基因检测药物
     *
     * @param geneticMedicineDto 基因检测药物信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateGeneticMedicine(GeneticMedicineDto geneticMedicineDto) {
        GeneticMedicine geneticMedicine = new GeneticMedicine();
        geneticMedicine.setId(geneticMedicineDto.getId());
        geneticMedicine.setDrugName(geneticMedicineDto.getDrugName());
        geneticMedicine.setDrugAlias(geneticMedicineDto.getDrugAlias());
        geneticMedicine.setCreateDateTime(new Date());
        int i = medicineRepository.updateGeneticMedicine(geneticMedicine);
        if (i > 0) {
            return new ApiResult<>(200, "success", "更新成功", null);
        } else {
            return new ApiResult<>(500, "failed", "更新失败", null);
        }
    }

    /**
     * 删除基因检测药物信息
     *
     * @param id 基因检测药物id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult deleteGeneticMedicine(String id) {
        int i = medicineRepository.deleteGeneticMedicine(id);
        if (i > 0) {
            return new ApiResult<>(200, "success", "删除成功", null);
        } else {
            return new ApiResult<>(500, "failed", "删除失败", null);
        }
    }

    /**
     * 获取所有的基因检测药物
     *
     * @return
     */
    @Override
    public ApiResult<List<GeneticMedicineDto>> geneticMedicineDtos() {
        List<GeneticMedicineDto> geneticMedicineDtos = medicineRepository.getGeneticMedicineDtos();
        return new ApiResult<>(200, "success", "获取基因检测药物数据成功", geneticMedicineDtos);
    }

    /**
     * 添加癌症药物信息
     *
     * @param geneticCancerMedicine 数据信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult insertGeneticCancerMedicine(GeneticCancerMedicine geneticCancerMedicine) {
        GeneticCancerMedicine cancerMedicine = medicineRepository.getCancerMedicineByCancerId(geneticCancerMedicine.getCancerId());
        int i = 0;
        //判断此癌症药物是否存在，如果存在则进行更新操作，否则进行添加操作
        if (cancerMedicine != null) {
            cancerMedicine.setDrugId(geneticCancerMedicine.getDrugId());
            i = medicineRepository.updateGeneticCancerMedicine(cancerMedicine);
        } else {
            ApiResult<GeneratorDto> apiResult = generatorService.getGenerator("genetic_cancer_medicine", null);
            geneticCancerMedicine.setDelFlag(false);
            geneticCancerMedicine.setId(apiResult.getData().getSerialNumber());
            i = medicineRepository.insertGeneticCancerMedicine(geneticCancerMedicine);
        }
        if (i > 0) {
            return new ApiResult<>(200, "success", "添加成功", null);
        } else {
            return new ApiResult<>(500, "failed", "添加失败", null);
        }
    }

    /**
     * 癌症药物列表
     *
     * @param geneticMedicineCondition 查询条件
     * @return 列表信息
     */
    @Override
    public ApiResult<Pagination<GeneticCancerMedicineDto>> cancerMedicinePage(GeneticMedicineCondition geneticMedicineCondition) {
        FieldChecker.checkEmpty(geneticMedicineCondition.getLimitHelper(), "limitHelper");
        int count = medicineRepository.geneticCancerMedicineCount(geneticMedicineCondition);
        Pagination<GeneticCancerMedicineDto> pagination = Pagination.newInstance(geneticMedicineCondition.getLimitHelper(), count);
        List<GeneticCancerMedicineDto> geneticCancerMedicineDtos = new ArrayList<>();
        if (count > 0) {
            geneticCancerMedicineDtos = medicineRepository.geneticCancerMedicineDtos(geneticMedicineCondition);
            if (geneticCancerMedicineDtos != null && geneticCancerMedicineDtos.size() > 0) {
                //处理查询出来的数据
                geneticCancerMedicineDtos.forEach(geneticCancerMedicineDto -> {
                    if (!StringUtils.isEmpty(geneticCancerMedicineDto.getDrugId())) {
                        //查询肿瘤对应的药物名称
                        String medicineNames = getMedicineNames(geneticCancerMedicineDto.getDrugId());
                        geneticCancerMedicineDto.setDrugName(medicineNames);
                    }
                });
            }
        }
        pagination.setResult(geneticCancerMedicineDtos);
        return new ApiResult<>(200, "success", "查询癌症药物列表成功", pagination);
    }

    /**
     * 根据id获取信息
     *
     * @param id id
     * @return 数据信息
     */
    @Override
    public ApiResult<GeneticCancerMedicineDto> cancerMedicineById(String id) {
        GeneticCancerMedicineDto cancerMedicineDto = medicineRepository.cancerMedicineById(id);
        if (!StringUtils.isEmpty(cancerMedicineDto.getDrugId())) {
            String medicineNames = getMedicineNames(cancerMedicineDto.getDrugId());
            cancerMedicineDto.setDrugName(medicineNames);
        }
        String cancerName = medicineRepository.getCancerName(cancerMedicineDto.getParentId());
        cancerMedicineDto.setParentName(cancerName);
        return new ApiResult<>(200, "success", "获取药物信息成功", cancerMedicineDto);
    }

    /**
     * 删除癌症药物
     *
     * @param id id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult deleteCancerMedicine(String id) {
        int i = medicineRepository.deleteCancerMedicine(id);
        if (i > 0) {
            return new ApiResult(200, "success", "删除成功", null);
        } else {
            return new ApiResult(500, "failed", "删除失败", null);
        }
    }

    /**
     * 更新癌症药物信息
     *
     * @param geneticCancerMedicine
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateCancerMedicine(GeneticCancerMedicine geneticCancerMedicine) {
        int i = medicineRepository.updateGeneticCancerMedicine(geneticCancerMedicine);
        if (i > 0) {
            return new ApiResult(200, "success", "更新成功", null);
        } else {
            return new ApiResult(500, "failed", "更新失败", null);
        }
    }

    /**
     * 根据父级id查询疾病信息
     *
     * @param parentId 父级id
     * @return 疾病信息
     */
    @Override
    public ApiResult<List<DaCancerDto>> cancerInfoByParentId(String parentId) {
        List<DaCancerDto> daCancerDtos = medicineRepository.cancerInfoByParentId(parentId);
        return new ApiResult<>(200, "success", "获取疾病信息成功", daCancerDtos);
    }

    @Override
    public ApiResult<List<GeneticCancerMedicineDto>> cancerMedicineAll() {
        List<GeneticCancerMedicineDto> list=medicineRepository.cancerMedicineAll();
        return ApiResult.succ(list);
    }

    /**
     * 基因检测药物列表（花生仁）
     * @return
     */
    @Override
    public ApiResult peanutDrugs() {
        List<GeneticMedicineDto> geneticMedicineDtos = medicineRepository.peanutDrugs();
        return new ApiResult(200,"success","数据获取成功",geneticMedicineDtos);
    }

    /***
     * 根据id获取疾病
     * @author jcl
     * @date 2018/10/26 14:18
     * @param cancerId 疾病id
     * @return
     */
    @Override
    public ApiResult cancerById(String cancerId) {
        DaCancerDto daCancerDto = medicineRepository.cancerById(cancerId);
        return new ApiResult(200,"success","数据获取成功",daCancerDto);
    }

    /**
     * 根据id获取药物名称
     *
     * @param medicineId
     * @return 药物名称
     */
    public String getMedicineNames(String medicineId) {
        String[] medicineIds = medicineId.split(",");
        List<String> names = medicineRepository.geneticNameByIds(medicineIds);
        String[] s = new String[names.size()];
        String[] strings = names.toArray(s);
        return StringUtils.arrayToDelimitedString(strings, ",");
    }
}
